package com.lu.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.lu.system.management.domain.UserDO;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 处理token
 */
public class TokenUtils {

    //密钥
    private static String JWT_SECRET="8677df7fc3a34e26a61c034d5ec8245d";


    /**
     * 创建 jwt
     * @param subject
     * @return
     * @throws Exception
     */
    public  static String createJWT(String subject) throws Exception {

        SecretKey key = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key);

        return builder.compact();
    }



    /**
     * 由字符串生成加密key
     * @return
     */
    public static SecretKey generalKey(){
        byte[] encodedKey = Base64.decodeBase64(JWT_SECRET);//本地的密码解码[B@152f6e2
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// 根据给定的字节数组使用AES加密算法构造一个密钥，使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。
        return key;
    }


    /**
     * 解密jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception{
        SecretKey key = generalKey();  //签名秘钥，和生成的签名的秘钥一模一样

        return Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
    }


    /**
     * 增加token的有效期
     */
    public static  void  addTokenTime(String jwt,long ttlMillis){

        SecretKey key = generalKey();  //签名秘钥，和生成的签名的秘钥一模一样
        Claims claims = Jwts.parser()  //得到DefaultJwtParser
                .setSigningKey(key)         //设置签名的秘钥
                .parseClaimsJws(jwt).getBody();//设置需要解析的jwt
        Date exp = new Date(ttlMillis);
        claims.setExpiration(exp);
    }


    /**
     * 解析token获取用户信息
     * @param request
     * @return
     */
    public static UserDO parseJwtForUserInfo(HttpServletRequest request) throws Exception {
//        String access_token = request.getHeader("access_token");
        String access_token = request.getParameter("access_token");
        String subject = TokenUtils.parseJWT(access_token).getSubject();
        UserDO userDO = JSONObject.parseObject(subject, UserDO.class);
        return userDO;
    }








}
